package util

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"math/rand"
	"time"
)

/**
 *
 * @return
 */
func Typeof(v interface{}) string {
	return fmt.Sprintf("%T", v)
}

/**
 *
 * @return
 */
func Json2Bytes(v *interface{}) ([]byte, error) {
	var _buf bytes.Buffer
	_enc := json.NewEncoder(&_buf)
	_enc.SetEscapeHTML(false)
	if _err := _enc.Encode(*v); nil != _err {
		return nil, _err
	}
	return _buf.Bytes(), nil
}

/**
 *
 * @return
 */
func Str2Json(v []byte) (map[string]interface{}, error) {
	var _v map[string]interface{}
	if _err := json.Unmarshal(v, &_v); nil != _err {
		return nil, _err
	}
	return _v, nil
}

/**
 *
 * @return
 */
func GenSignature(key, data string) string {
	_hmac := hmac.New(sha1.New, []byte(key))
	_hmac.Write([]byte(data))
	return base64.StdEncoding.EncodeToString(_hmac.Sum([]byte(nil)))
}

/**
 * 生成随机数字
 *
 * @return
 */
func GenRandInt(min int, max int) int {
	rand.Seed(time.Now().UnixNano())
	_random := rand.Intn(max - min)
	_random = min + _random
	return _random
}
